package servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(name = "CheckCodeServlet", value = "/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 创建缓冲图像
        int width=80;
        int height=30;
        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取图形上下文
        Graphics2D g2 = (Graphics2D) bi.getGraphics();
        // 设置背景颜色
        g2.setColor(Color.WHITE);
        g2.fillRect(0, 0, width, height);
        // 绘制边框
        g2.setColor(Color.BLUE);
        g2.drawRect(0, 0, width - 1, height - 1);
        // 设置验证码字符集
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        chars = "0123456789";
        // 生成验证码字符串
        Random r = new Random();
        String checkcode = "";
        for (int i = 0; i < 4; i++) {
            checkcode += chars.charAt(r.nextInt(chars.length()));
        }
        // 将验证码存储在session中
        request.getSession().setAttribute("checkcode", checkcode);
        // 设置验证码颜色
        g2.setColor(Color.RED);
        g2.setFont(new Font("Arial", Font.BOLD, 20));
        g2.drawString(checkcode, 10, 20);
        // 绘制噪声线
        g2.setColor(Color.green);
        for (int i = 0; i < 5; i++) {
            int x1=r.nextInt(80);
            int x2=r.nextInt(80);
            int y1=r.nextInt(30);
            int y2=r.nextInt(30);
            g2.drawLine(x1,y1,x2,y2);
        }
        // 释放图形上下文资源
        g2.dispose();
        // 输出图像
        ImageIO.write(bi, "png", response.getOutputStream());
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
          doGet(request,response);
    }
}
